package com.fzk.blog.blog.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.fzk.blog.bean.Comment;
import com.fzk.blog.bean.vo.CommentInfo;
import com.fzk.blog.blog.service.ICommentService;
import com.fzk.blog.exception.MyException;
import com.fzk.blog.utils.ResponseResult;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Map;

/**
 * @author fzk
 * @date 2021-08-23 17:38
 */
@RestController
public class CommentController {
    @Resource
    private ICommentService commentService;

    @GetMapping(path = "/blog/comment/info")
    public Map<String, Object> getCommentInfoListOrOne(
            @RequestParam(name = "id", required = false) BigInteger id,
            @RequestParam(name = "blog_id", required = false) Integer blogId,
            @RequestParam(name = "user_id", required = false) Integer userId,
            @RequestParam(name = "page_no", required = false) Integer pageNo,
            @RequestParam(name = "page_size", required = false) Integer pageSize
    ) {
        // 1.判断id
        if (id != null) {
            // 2.1 特定查询评论info
            CommentInfo commentInfo = commentService.getCommentInfoById(id);
            return ResponseResult.success("查询成功", commentInfo);
        } else {
            // 2.2 查询列表，可能是分页查询哦
            Map<String, Object> returnMap = commentService.getCommentInfoListCondition(blogId, userId, pageNo, pageSize);
            returnMap.put("code", 200);
            returnMap.put("msg", "查询成功");
            return returnMap;
        }
    }

    @PostMapping(path="/blog/comment")
    @SaCheckLogin//检查登录
    public Map<String,Object> insertComment(
            @RequestParam("content")String content,
            @RequestParam("blog_id")int blogId
    ){
        // 1.取出loginId
        int loginId= Integer.parseInt(StpUtil.getLoginId().toString());

        // 2.参数判断
        if(Strings.trimToNull(content)==null)
            throw new MyException(400,"参数错误：评论不能为空");

        // 3.装入参数
        Comment comment=new Comment();
        comment.setBlogId(blogId);
        comment.setContent(content);

        // 4.调用service
        CommentInfo commentInfo=commentService.insertComment(comment,loginId);

        return ResponseResult.success("评论成功",commentInfo);
    }
}
